//
//  PhotoSlideViewController.m
//  AiQiChe
//
//  Created by lian jie on 7/31/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PhotoSlideViewController.h"

@interface PhotoSlideViewController()
- (void)dismiss;
- (ImageZoomableView *)dequeueRecycledPage;
- (void)recycleImageViews;
- (void)setupPageForIndex:(int)index;
- (int)getImageCount;
- (int)getPreviouIndex;
- (int)getNextIndex;
- (CGRect)frameForPageAtIndex:(NSInteger)index;
- (CGRect)frameForPageAtIndex:(NSInteger)index orientation:(UIInterfaceOrientation)orientation;
- (BOOL)shouldShowPageForIndex:(int)index;
- (BOOL)isShowingPageForIndex:(int)index;
- (ImageZoomableView*)pageForIndex:(int)index;
- (void)restoreZoomScaleForInvisiblePages;
- (void)clearPage;
- (void)setImageScrollViewContentSize;
- (void)setImageScrollViewContentSizeForOrientation:(UIInterfaceOrientation)orientation;
- (void)adjustImageAlphaWhenScrolled;
@end

@implementation PhotoSlideViewController
@synthesize imageScrollView = _imageScrollView;
@synthesize navView = _navView;
@synthesize contentView;

#pragma mark - private methods

- (IBAction)shareImage:(id)sender {
}
- (IBAction)favImage:(id)sender {
}


- (void)clearPage{
    [_recycledViewSet removeAllObjects];
    [_imageScrollView removeAllSubviews];
}
- (void)dismiss{
    [self clearPage];
    //    [self.view removeFromSuperview];
    UIView *superview = self.contentView.superview;
    [self.navigationController popViewControllerAnimated:YES];
    CATransition *animation = [CATransition animation];
    [animation setType:kCATransitionFade];
    [animation setDelegate:self];
    [animation setDuration:0.5];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [[superview layer] addAnimation:animation forKey:@""];
    [self.contentView removeFromSuperview];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if (flag) {
    }
}

- (int)getImageCount{
    return [_images count];
}

- (int)getPreviouIndex{
    return MAX(0, _currentIndex - 1);
}
- (int)getNextIndex{
    return MIN([self getImageCount] - 1, _currentIndex + 1);
}
- (BOOL)shouldShowPageForIndex:(int)index{
    return (index == _currentIndex || 
            index == [self getPreviouIndex] || 
            index == [self getNextIndex]);
}
- (ImageZoomableView *)dequeueRecycledPage{
    ImageZoomableView *page = [_recycledViewSet anyObject];
    if (page) {
        [[page retain] autorelease];
        [_recycledViewSet removeObject:page];
    }else{
        //create one
        page = [[[ImageZoomableView alloc] initWithFrame:_imageScrollView.bounds] autorelease];
        page.tapDelegate = self;
        page.index = -1;
    }
    return page;
}

- (ImageZoomableView*)pageForIndex:(int)index{
    ImageZoomableView *page = nil;
    for (UIView *view in [_imageScrollView subviews]) {
        if (![view isKindOfClass:[ImageZoomableView class]]) {
            continue;
        }
        int indexOfView = ((ImageZoomableView*)view).index;
        if (indexOfView == index) {
            page = (ImageZoomableView*)view;
            break;
        }
    }
    return page;
}
- (CGRect)frameForPageAtIndex:(NSInteger)index {
    UIInterfaceOrientation currentOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    return [self frameForPageAtIndex:index orientation:currentOrientation];
}
- (CGRect)frameForPageAtIndex:(NSInteger)index orientation:(UIInterfaceOrientation)orientation{
    CGRect bounds = _imageScrollView.bounds;
	CGRect pageFrame = bounds;
	pageFrame.origin.x = (bounds.size.width * index);
    pageFrame.origin.y = 0;
	return pageFrame;
    
}

- (void)recycleImageViews{
    //recycle big image views
    for (UIView *view in [_imageScrollView subviews]) {
        if (![view isKindOfClass:[ImageZoomableView class]]) {
            continue;
        }
        int indexOfView = ((ImageZoomableView*)view).index;
        if (![self shouldShowPageForIndex:indexOfView]) {
            [_recycledViewSet addObject:view];
            [(ImageZoomableView*)view cancelImageRequest];
            [(ImageZoomableView*)view  displayImage:nil];
            [view removeFromSuperview];
            ITTDINFO(@"page %d is recycled,current recycled object:%d", indexOfView,[_recycledViewSet count]);
        }
    }
    
}
- (BOOL)isShowingPageForIndex:(int)index{
    BOOL isShowing = NO;
    for (UIView *view in [_imageScrollView subviews]) {
        if (![view isKindOfClass:[ImageZoomableView class]]) {
            continue;
        }
        int indexOfView = ((ImageZoomableView*)view).index;
        if (indexOfView == index) {
            isShowing = YES;
            break;
        }
    }
    return  isShowing;
}

- (void)restoreZoomScaleForInvisiblePages{
    
    for (UIView *view in [_imageScrollView subviews]) {
        if (![view isKindOfClass:[ImageZoomableView class]]) {
            continue;
        }
        
        int indexOfView = ((ImageZoomableView*)view).index;
        if (indexOfView == _currentIndex) {
            continue;
        }
        [(ImageZoomableView*)view setZoomScale:[(ImageZoomableView*)view minimumZoomScale] animated:YES];
    }
}

- (void)adjustImageAlphaWhenScrolled{
    for (UIView *view in [_imageScrollView subviews]) {
        if (![view isKindOfClass:[ImageZoomableView class]]) {
            continue;
        }
        
        int indexOfView = ((ImageZoomableView*)view).index;
        if (indexOfView == _currentIndex) {
            [UIView animateWithDuration:0.2 animations:^{
                ((ImageZoomableView*)view).alpha = 1;
            }];
        }else{
            ((ImageZoomableView*)view).alpha = 0.9;
        }
    }
}

- (void)setupPageForIndex:(int)index{
    if ([self isShowingPageForIndex:index]) {
        return;
    }
    ImageZoomableView *page = [self dequeueRecycledPage];
    if (page.index != index) {
        ITTDINFO(@"reusing page: original index is %d, new index is %d", page.index , index);
        page.frame = [self frameForPageAtIndex:index];
        page.index = index;
        [_imageScrollView addSubview:page];
        [page displayImage:[_images objectAtIndex:index]];
    }else{
        ITTDINFO(@"reusing page directly");
    }
}

- (void)tilePages {
	// Calculate which pages are visible
    //	CGRect visibleBounds = _imageScrollView.bounds;
    //	_currentIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds));
    //    
    //	_currentIndex = MAX(_currentIndex,0);
    //	_currentIndex = MIN(_currentIndex,[self getImageCount] + 1);
    /*
     BOOL shouldUpdate = NO;
     if (_oldCurrentIndex != _currentIndex) {
     shouldUpdate = YES;
     _oldCurrentIndex = _currentIndex;
     }
     if (!shouldUpdate) {
     return;
     }
     */
    [self recycleImageViews];
    
    [self setupPageForIndex:_currentIndex];
    [self setupPageForIndex:[self getNextIndex]];
    [self setupPageForIndex:[self getPreviouIndex]];
}

- (void)setImageScrollViewContentSize{
    UIInterfaceOrientation currentOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    [self setImageScrollViewContentSizeForOrientation:currentOrientation];
}
- (void)setImageScrollViewContentSizeForOrientation:(UIInterfaceOrientation)orientation{
    CGRect bounds = _imageScrollView.bounds;    
    _imageScrollView.contentSize = CGSizeMake(bounds.size.width * [self getImageCount],bounds.size.height );
}

- (void)scrollToindex:(NSInteger)index{
    CGRect targetFrame = [self frameForPageAtIndex:index];
    [_imageScrollView setContentOffset:targetFrame.origin animated:NO];
}

#pragma mark - ScrollView delegate methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	//[self setNeedsDisplay];
    CGRect visibleBounds = _imageScrollView.bounds;
	NSInteger index = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds));
    
	index = MAX(index,0);
	index = MIN(index,[self getImageCount] + 1);
    if (index!=_currentIndex) {
        _currentIndex = index;
        [self tilePages];
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self restoreZoomScaleForInvisiblePages];
    [self adjustImageAlphaWhenScrolled];
}
#pragma mark - public methods

- (IBAction)backBtnClicked:(id)sender {
    [self dismiss];
}

- (IBAction)shareBtnClicked:(id)sender{
    UIActionSheet * sheet = [[UIActionSheet alloc] initWithTitle:@"分享照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"微博分享",@"邮件分享",@"保存到相册",nil];
    [sheet showFromRect:[(UIView *)sender frame] inView:self.contentView animated:YES];
    [sheet release];
}



- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {	 
    if (result == MFMailComposeResultSent) {
        [UIAlertView popupAlertByDelegate:self Title:@"提示" Message:@"邮件分享成功"];
    }else if(result == MFMailComposeResultCancelled){
    }
}

-(id)initWithImages:(NSMutableArray *)images selectedIndex:(int)selectedIndex
{
    self = [super initWithNibName:@"PhotoSlideViewController" bundle:nil];
    if (self) {
        _recycledViewSet = [[NSMutableSet alloc] init];
        if (images != nil) {
            _images = [images retain];  
        }
        _currentIndex = selectedIndex;
    }
    return self;
}

- (UIImage *)currentImage{
    return [self pageForIndex:_currentIndex].image;
}

- (NSString *)currentPid{
//    return ((ATPImage*)[_images objectAtIndex:_currentIndex]).photoId;
    return nil;
}

- (void)dealloc{
    _currentIndex = 0;
    RELEASE_SAFELY(_images);
    RELEASE_SAFELY(_recycledViewSet);
    [favButton release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

-(void)setVerticalFrame 
{ 
    _navView.height = 100;
    favButton.left = 340;
}

-(void)setHorizontalFrame 
{ 
    _navView.height = 80;
    favButton.left = 467;
}

- (void)adjustViews:(UIInterfaceOrientation)orientation{
    if (UIInterfaceOrientationIsLandscape(orientation)) {
        [self setHorizontalFrame];
    }else{
        [self setVerticalFrame];
    }
}
#pragma mark - View lifecycle

- (void)viewDidLoad{
    [super viewDidLoad];
    [self.contentView setBackgroundColor:[UIColor blackColor]];
    //[self.view setAlpha:0.8];
    self.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    _imageScrollView.frame = CGRectMake(0, 0, self.contentView.width, self.contentView.height);
    _imageScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self adjustViews:[UIApplication sharedApplication].statusBarOrientation];
    [self.navigationController setNavigationBarHidden:YES animated:NO];   
    self.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self.contentView bringSubviewToFront:_navView];
    
    [self setImageScrollViewContentSize];
    
    [self tilePages];
    [self scrollToindex:_currentIndex];
    
    // scroll to current index
}

- (void)viewDidUnload{
    [favButton release];
    favButton = nil;
    [super viewDidUnload];
    RELEASE_SAFELY(_imageScrollView);
    RELEASE_SAFELY(_navView);
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}

- (void)viewDidAppear:(BOOL)animated{
    //    [UIView animateWithDuration:0.5 
    //                     animations:^{
    //                         self.view.frame = [[ApplicationSkeleton sharedSkeleton] view].bounds;
    //                         [[[ApplicationSkeleton sharedSkeleton] view] addSubview:self.view];
    //                     }];
    [super viewDidAppear:animated];
    //    if (_initSelectedIndex >= 0) {
    //        CGRect targetFrame = [self frameForPageAtIndex:_initSelectedIndex];
    //        [_imageScrollView setContentOffset:targetFrame.origin animated:NO];
    //        [_thumbnailScrollView scrollToIndex:_initSelectedIndex];
    //    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    // Return YES for supported orientations
    _indexBeforeRotation = _currentIndex;
    return YES;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [self adjustViews:toInterfaceOrientation];
    [self setImageScrollViewContentSizeForOrientation:toInterfaceOrientation];
    _currentIndex = _indexBeforeRotation;
    [self tilePages];
    [self pageForIndex:_currentIndex+1].hidden = YES;
    [self pageForIndex:_currentIndex-1].hidden = YES;
    for (UIView *view in [_imageScrollView subviews]) {
        if (![view isKindOfClass:[ImageZoomableView class]]) {
            continue;
        }
        ImageZoomableView *page = (ImageZoomableView*)view;
        if (page.index == _currentIndex) {
            [UIView animateWithDuration:duration animations:^{
                page.frame = [self frameForPageAtIndex:page.index];
                [page setMaxMinZoomScalesForCurrentBounds];
                [page restoreCenterPoint:[page pointToCenterAfterRotation] scale:[page scaleToRestoreAfterRotation]];
            }];
            [page setZoomScale:page.minimumZoomScale animated:NO];
        }else{
            page.frame = [self frameForPageAtIndex:page.index];
        }
    }
    [self scrollToindex:_currentIndex];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
    [self pageForIndex:_currentIndex+1].hidden = NO;
    [self pageForIndex:_currentIndex-1].hidden = NO;
}


#pragma mark - ImageZoomableViewDelegate
- (void)imageZoomableViewSingleTapped:(ImageZoomableView*)imageZoomableView{
    
}

@end
